//
//  LSZVideoPlaybackViewController.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/8/28.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZVideoPlaybackViewController.h"
#import "JDVideoModel.h"
#import "JDPlayerView.h"
#import "JDPlayer.h"
@interface LSZVideoPlaybackViewController ()<JDPlayerDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>
@property(nonatomic,assign) BOOL applicationIdleTimerDisabled;
@property(nonatomic,assign) BOOL shouldRotate;

//@property(nonatomic,strong) AVPlayer* player;
@property(nonatomic,strong) NSString * playUrl;
@property(nonatomic,strong) JDPlayer* player;
@property(nonatomic,strong) UITableView * tableViewList;
@property(nonatomic,strong) UITableView * tableViewIntroduction;
//请求得到的相关的数据

@property(nonatomic,strong)UIScrollView * scrollViewBack;

@property(nonatomic,strong)UIImageView * imageViewBack;//还没点击视频的占位图片
@property(nonatomic,strong)NSMutableArray * arrayMutData;//得到的目录数据

@property(nonatomic,strong)UIButton * butIntroduction;
@property(nonatomic,strong)UIButton * butDirectory;
@property(nonatomic,strong)UIView * viewRed;


@property(nonatomic,assign) NSInteger totalValuer;//学习时间
@property(nonatomic,strong) NSTimer * timer;//计时器
@end

@implementation LSZVideoPlaybackViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden=YES;
    self.applicationIdleTimerDisabled = [UIApplication sharedApplication].isIdleTimerDisabled;
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [self getTheRecommendedVideoFirst];//先获取目录的视频
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.tabBarController.tabBar.hidden=NO;
    [self.player pauseContent];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = self.applicationIdleTimerDisabled;
    [self.timer invalidate];
    self.timer = nil;
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
    self.view.backgroundColor = [UIColor whiteColor];
    self.arrayMutData = [[NSMutableArray alloc]init];
    self.shouldRotate = YES;
    [self addObserver];
//    [self.tableViewList registerClass:[LSZBDetailsPlayTableViewCell class] forCellReuseIdentifier:@"LSZBDetailsPlayTableViewCell"];
//    [self.tableViewList registerClass:[LSZBInformationTableViewCell class] forCellReuseIdentifier:@"LSZBInformationTableViewCell"];
//    [self.tableViewList registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    ///请求广告
    
    self.imageViewBack = [[UIImageView alloc]init];
    if (iPhoneX ) {
        self.imageViewBack.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16+24);
    }else{
        self.imageViewBack.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);
    }
    self.imageViewBack.userInteractionEnabled = YES;
    [self.imageViewBack sd_setImageWithURL:[NSURL URLWithString:self.imageViewOver] placeholderImage:[UIImage imageNamed:@"默认"]];
    [self.view addSubview:self.imageViewBack];
    
    UIButton * butReturn = [[UIButton alloc]init];
    butReturn.frame = CGRectMake(20, NAVIGATION_BAR_HEIGHT-40, 40, 40);
    [butReturn setImage:[UIImage imageNamed:@"jd_done_icon"] forState:UIControlStateNormal];
    [butReturn addTarget:self action:@selector(clickImgReturn) forControlEvents:UIControlEventTouchUpInside];
    [self.imageViewBack addSubview:butReturn];
    
    
    [self setUI];
    //下面是视频  先暂时隐藏
}
-(void)clickImgReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UI布局
-(void)setUI
{
    CGFloat height;
    if (iPhoneX ) {
        height = ScreenWidth*9/16+24;
    }else{
        height = ScreenWidth*9/16;
    }
    
    self.butIntroduction = [[UIButton alloc]init];
    self.butIntroduction.frame = CGRectMake(0, height, ScreenWidth/2, 60);
    [self.butIntroduction setTitle:@"简介" forState:UIControlStateNormal];
    [self.butIntroduction setTitleColor:themeColor forState:UIControlStateNormal];
    [self.butIntroduction addTarget:self action:@selector(clickButIntroduction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.butIntroduction];
    
    self.butDirectory = [[UIButton alloc]init];
    self.butDirectory.frame = CGRectMake(CGRectGetMaxX(self.butIntroduction.frame), height, ScreenWidth/2, 60);
    [self.butDirectory setTitle:@"目录" forState:UIControlStateNormal];
    [self.butDirectory setTitleColor:titleColorLSZ forState:UIControlStateNormal];
    [self.butDirectory addTarget:self action:@selector(clickDirectory) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.butDirectory];
    UIView * viewFen = [[UIView alloc]init];
    viewFen.backgroundColor = dividerColor;
    viewFen.frame = CGRectMake((ScreenWidth-1)/2, CGRectGetMinY(self.butIntroduction.frame), 1, self.butIntroduction.frame.size.height);
    [self.view addSubview:viewFen];
    
    self.viewRed = [[UIView alloc]init];
    self.viewRed.frame = CGRectMake(ScreenWidth/6,CGRectGetMaxY(self.butDirectory.frame)-4, ScreenWidth/6, 1.5);
    self.viewRed.backgroundColor = themeColor;
    [self.view addSubview:self.viewRed];
    
    self.scrollViewBack = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.butIntroduction.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(self.butIntroduction.frame)-HOME_INDICATOR_HEIGHT)];
    self.scrollViewBack.delegate = self;
    self.scrollViewBack.bounces = NO; // 默认为YES 取消设置NO
    // 当bounces属性为NO时，以下两个属性设置无效
    self.scrollViewBack.alwaysBounceHorizontal = YES; // 水平方向弹簧效果
    self.scrollViewBack.alwaysBounceVertical = YES; // 垂直方向弹簧效果
    self.scrollViewBack.decelerationRate = 0.1; // 值域 0~1 值越小减速停止的时间越短
    self.scrollViewBack.pagingEnabled = YES; // 默认为NO，设置YES内容视图整页滚动
    self.scrollViewBack.showsVerticalScrollIndicator = YES; // 垂直方向
    self.scrollViewBack.contentSize = CGSizeMake(ScreenWidth*2, ScreenHeight-CGRectGetMaxY(self.butIntroduction.frame));
    [self.view addSubview:self.scrollViewBack];
    
    
    _tableViewIntroduction = [[UITableView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, self.scrollViewBack.frame.size.height) style:UITableViewStyleGrouped];
    _tableViewIntroduction.dataSource =self;
    _tableViewIntroduction.delegate = self;
    _tableViewIntroduction.estimatedRowHeight=0;
    _tableViewIntroduction.estimatedSectionFooterHeight =0;
    _tableViewIntroduction.estimatedSectionHeaderHeight =0;
    [self.scrollViewBack addSubview:_tableViewIntroduction];
    
    
    _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth,0, ScreenWidth, self.scrollViewBack.frame.size.height) style:UITableViewStyleGrouped];
    _tableViewList.dataSource =self;
    _tableViewList.delegate = self;
    _tableViewList.estimatedRowHeight=0;
    _tableViewList.estimatedSectionFooterHeight =0;
    _tableViewList.estimatedSectionHeaderHeight =0;
    [self.scrollViewBack addSubview:_tableViewList];
    self.totalValuer = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(clickTimer) userInfo:nil repeats:YES];
    [self suspendedPlayer];
}
#pragma mark - 统计在线时长
-(void)clickTimer
{
    self.totalValuer = self.totalValuer+1;
    NSLog(@"统计时间>>>>>>>>>>%ld",(long)self.totalValuer);
    if(self.totalValuer == 90){
        self.totalValuer = 0;
        [LSZRequestData WatchAudioAndVideoFinished:@"90" paperId:self.id_id :^(BOOL isOk, NSString * str, NSString * string) {
            
        }];
    }
}
#pragma mark - 暂停播放
-(void)suspendedPlayer
{
    [self.timer setFireDate:[NSDate distantFuture]];
}
#pragma mark - 继续播放
-(void)continueToPlayer
{
    [self.timer setFireDate:[NSDate distantPast]];
}
#pragma mark - 简介
-(void)clickButIntroduction
{
    NSLog(@"简介简介简介简介");
    [self.scrollViewBack setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.butIntroduction setTitleColor:themeColor forState:UIControlStateNormal];
    [self.butDirectory setTitleColor:titleColorLSZ forState:UIControlStateNormal];
    CGRect frame = self.viewRed.frame;
    frame.origin.x = ScreenWidth/6;
    self.viewRed.frame = frame;
}
#pragma mark - 目录
-(void)clickDirectory
{
    NSLog(@"目录目录目录目录");
    [self.scrollViewBack setContentOffset:CGPointMake(ScreenWidth, 0) animated:YES];
    [self.butIntroduction setTitleColor:titleColorLSZ forState:UIControlStateNormal];
    [self.butDirectory setTitleColor:themeColor forState:UIControlStateNormal];
    CGRect frame = self.viewRed.frame;
    frame.origin.x = ScreenWidth/6*4;
    self.viewRed.frame = frame;
}
-(void)addNotificationCenter
{
    //返回键
    __weak typeof(self) weakSelf = self;
    self.player.jdView.doneButtonBlock = ^{
        [weakSelf.player pauseContent];
        [weakSelf suspendedPlayer];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    self.player.parseFailureBlock = ^{
        NSLog(@"解析失败");
        [weakSelf suspendedPlayer];
//        [weakSelf setStringWarning:@"解析失败!"];
        [weakSelf.player pauseContent];
    };
    self.player.jdView.doneStateYesButtonBlock = ^{
        [weakSelf continueToPlayer];
    };
    self.player.jdView.doneStateNoButtonBlock = ^{
        [weakSelf suspendedPlayer];
    };
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationSwitchScreen:) name:@"switchScreen" object:nil];//切换屏幕
}
#pragma mark - 首次播放的url
- (void)playVideo
{
//    self.playUrl = @"http://7xs8ft.com2.z0.glb.qiniucdn.com/rcd_vid_856a6738eefc495bbd7b0ed59beaa9fe";
//    JDVideoModel* videoModel = [[JDVideoModel alloc]init];
//    self.playUrl = [NSString stringWithFormat:@"%@?%ld",self.playUrl,(long)[self getInter]];//使用随机数是可以
//    videoModel.streamURL = [NSURL URLWithString:[self stringUrl:self.playUrl]];
//
////    videoModel.streamURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?scr=%d",self.playUrl,[self getInter]] relativeToURL:[NSURL URLWithString:[self stringUrl:self.playUrl]]];
//    [self.player loadVideoModel:videoModel];
}
-(NSString *)stringUrl :(NSString *)string
{
    //    NSString * playUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
    //    NSString * playUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
    //    return playUrl;
    //    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    //    NSString *encodeUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];
    
    NSString*playUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return playUrl;
}
-(int)getInter
{
    int x = arc4random() % 10000;
    return x;
}
#pragma mark - App States
- (void)applicationWillResignActive
{
    self.player.jdView.countdownToHide = -1;
    if (self.player.state == JDPlayerStatePlaying){
        [self.player pauseContent:NO recordCurrentTime:YES completionHandler:nil];
    }
}
- (void)applicationDidBecomeActive
{
    self.player.jdView.countdownToHide = -1;
}
#pragma mark - 所有的播放完毕 也会走这个方法
- (void)videoPlayer:(JDPlayer*)videoPlayer didPlayToEnd:(JDVideoModel *)videoModel
{
//    NSInteger beForeRow = self.recommendedClick;
//    if(self.isOffline == YES){
//        if (beForeRow == self.VideoOfflineManager.arrayData.count-1) {
//            NSLog(@"最后一个最后一个");
//            return;
//        }
//    }else{
//        if (beForeRow == self.relatedVideoManager.arrayData.count-1) {
//            NSLog(@"最后一个最后一个");
//            return;
//        }
//    }
//    self.recommendedClick = beForeRow+1;
    [self suspendedPlayer];
    [self.player pauseContent];
    
//    [self.baiduMobAdPrerollNative.nativeAdView removeFromSuperview];
//    [self didPlayAdClose];
//    [self loadPrerollNative];
    
//    [self butInVideo];
//    [self loadTheVideo];//再更新URL
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        // 刷新表格  和结束刷新
//        if(self.videoFailed == YES){
//            self.videoFailed = NO;
//        }else{
//            [self loadTheVideo];//再更新URL
//        }
//    });
    NSLog(@"走这个了走这个了走这个了走这个了走这个了走这个了走这个了走这个了");
}
- (void)handleErrorCode:(JDPlayerErrorCode)errorCode track:(JDVideoModel *)track customMessage:(NSString*)customMessage
{
    NSLog(@"errorCode : %ld,message : %@ , url : %@",(long)errorCode,customMessage,track.streamURL);
}
#pragma mark - Orientation
- (BOOL)shouldAutorotate
{
    return self.shouldRotate;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return self.shouldRotate;
}
- (JDPlayer *)player
{
    if(!_player){
        _player = [[JDPlayer alloc] init];
        _player.delegate = self;
        [self.view addSubview:_player.jdView];
        if (iPhoneX ) {
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16+24);//进度条
        }else{
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);//进度条
        }
        //        _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);//进度条
    }
    return _player;
}
- (BOOL)prefersStatusBarHidden
{
    return YES;
}
-(void)InfoNotificationSwitchScreen:(NSNotification *)notification
{
    NSDictionary * dic = notification.userInfo;
    NSString * screen = dic[@"screen"];
    if ([screen isEqualToString:@"1"]) {
        self.tableViewList.hidden = YES;
    }else{
        self.tableViewList.hidden = NO;
    }
}
- (void)addObserver
{
    NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
#pragma mark - 先获取推荐的视频
-(void)getTheRecommendedVideoFirst
{
    [LSZRequestDicData threeInterfaceForData:self.id_id :^(BOOL isOk, NSString * string, LSZTertiaryInterfaceManager * manager) {
        if(isOk == YES){
            [self.arrayMutData addObjectsFromArray:manager.arrayData];
            [self.tableViewList reloadData];
        }
    }];
}
#pragma mark - 用户对资源点赞    type,资源类型     1,音频 2，视频 3，文章，6祷告，7见证
#pragma mark - 对原始资源点赞

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]){
        return NO;
    }
    return  YES;
}

#pragma mark ________________ 目录列表______________________

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == self.tableViewIntroduction ){
        return 1;
    }else{
        return self.arrayMutData.count;//这个是数据
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.tableViewIntroduction ){
        CGFloat height = [LSZSpecialPackaging getHeightOfText:ScreenWidth height:ScreenHeight font:14 :self.introductionStr];
        return height;
    }else{
        return 50;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellIdentifier"];
    }
    if(tableView == self.tableViewList){
        LSZTertiaryInterfaceMg * mg = nil;
        mg = self.arrayMutData[indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@",mg.name];
    }else{
        cell.textLabel.text = self.introductionStr;
        cell.textLabel.numberOfLines = 0;
    }
    cell.textLabel.font = FONT_(14);
    cell.textLabel.textColor = titleColorLSZ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableViewList) {
        LSZTertiaryInterfaceMg * mg = nil;
        mg = self.arrayMutData[indexPath.row];
        if (self.imageViewBack.hidden == NO) {
            self.imageViewBack.hidden = YES;
            self.playUrl = mg.contentUrl;
//            [self playVideo];
            JDVideoModel* videoModel = [[JDVideoModel alloc]init];
            self.playUrl = [NSString stringWithFormat:@"%@?%ld",self.playUrl,(long)[self getInter]];//使用随机数是可以
            videoModel.streamURL = [NSURL URLWithString:[self stringUrl:self.playUrl]];
            
            [self.player loadVideoModel:videoModel];
            [self addNotificationCenter];
            self.totalValuer = 0;
            [self continueToPlayer];
        }else{
            NSLog(@"切换视频");
            [self.player pauseContent];
            [self suspendedPlayer];

            self.playUrl = [NSString stringWithFormat:@"%@?%ld",mg.contentUrl,(long)[self getInter]];//使用随机数是可以
            JDVideoModel* nextTrack = [[JDVideoModel alloc]init];
             nextTrack.streamURL = [NSURL URLWithString:[self stringUrl:self.playUrl]];
//            if(self.recommendedClick == self.relatedVideoManager.arrayData.count - 1){
//                nextTrack.hasNext = NO;//最后一个就设置no
//            }else{
//                nextTrack.hasNext = YES;
//            }
            [self.player loadVideoModel:nextTrack];
            self.totalValuer = 0;
            [self continueToPlayer];
        }
    }
//    if(indexPath.section == 0&&self.isOffline == NO){
//        return;
//    }else if ((indexPath.section == 1&&self.isOffline == NO)||(indexPath.section == 0&&self.isOffline == YES)){
//        NSLog(@"广告");
//    }else{
//        NSInteger beForeRow = self.recommendedClick;
//        if(beForeRow == indexPath.row){
//            return;
//        }
//        self.recommendedClick = indexPath.row;
//        //        self.VideoOfflineManager.arrayData[self.recommendedClick];
//        if(self.VideoOfflineManager.arrayData.count > self.recommendedClick){
//            return;
//        }
//        [self.player pauseContent];
//        [self.baiduMobAdPrerollNative.nativeAdView removeFromSuperview];
//        [self didPlayAdClose];
//        [self loadPrerollNative];
//        [self butInVideo];//先刷新界面
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 刷新表格  和结束刷新
//            if(self.videoFailed == YES){
//                self.videoFailed = NO;
//            }else{
//                [self loadTheVideo];//再更新URL
//            }
//        });
//    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.navigationController.delegate = nil;
}

@end
